import { PageContainer } from '@ant-design/pro-components';
// 添加 Monaco Editor 用于代码编辑
import Editor from '@monaco-editor/react';
import { history, useParams } from '@umijs/max';
import {
  Button,
  Card,
  Col,
  Divider,
  message,
  Row,
  Slider,
  Spin,
  Typography,
} from 'antd';
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useRef, useState } from 'react';
import {
  getChartByIdUsingGet,
  regenerateChartUsingPost,
  updateChartUsingPost,
} from '@/services/yubi/chartController';

const { Title, Text } = Typography;

/**
 * 图表详情页面
 * @constructor
 */
const ChartDetailPage: React.FC = () => {
  const [chart, setChart] = useState<API.Chart>();
  const [loading, setLoading] = useState<boolean>(true);
  const [regenerating, setRegenerating] = useState<boolean>(false);
  const [updating, setUpdating] = useState<boolean>(false); // 添加更新状态
  const [chartHeight, setChartHeight] = useState<number>(400); // 图表高度状态（像素值）
  const [chartWidth, setChartWidth] = useState<number>(100); // 图表宽度状态（百分比）
  const [jsonCode, setJsonCode] = useState<string>(''); // JSON代码状态
  const [isEditorReady, setIsEditorReady] = useState<boolean>(false); // 编辑器是否准备就绪
  const params = useParams();
  const chartId = params.id;
  const chartRef = useRef<any>(null);

  /**
   * 获取图表详情
   */
  const fetchChartDetail = async () => {
    if (!chartId) {
      message.error('参数错误');
      history.push('/my_chart');
      return;
    }

    try {
      setLoading(true);
      const res = await getChartByIdUsingGet({ id: chartId });
      if (res.data) {
        setChart(res.data);
        // 初始化JSON代码
        setJsonCode(res.data.genChart || '{}');
      } else {
        message.error('获取图表详情失败');
        history.push('/my_chart');
      }
    } catch (e: any) {
      message.error('获取图表详情失败: ' + e.message);
      history.push('/my_chart');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 重新生成图表
   */
  const handleRegenerate = async () => {
    if (!chartId) {
      message.error('参数错误');
      return;
    }

    try {
      setRegenerating(true);
      // 修复参数传递问题，使用 chartId 作为参数
      const res = await regenerateChartUsingPost({ chartId: chartId as any });

      if (res.code === 0) {
        message.success('图表重新生成任务已提交');
        // 轮询获取最新状态
        await pollChartStatus();
      } else {
        message.error('重新生成失败: ' + res.message);
      }
    } catch (e: any) {
      message.error('重新生成失败: ' + e.message);
    } finally {
      setRegenerating(false);
    }
  };

  /**
   * 更新图表配置到数据库
   */
  const handleUpdateChart = async () => {
    if (!chartId) {
      message.error('参数错误');
      return;
    }

    try {
      // 验证JSON格式
      JSON.parse(jsonCode);
    } catch (e: any) {
      message.error('JSON格式错误: ' + e.message);
      return;
    }

    try {
      setUpdating(true);
      // 准备更新数据
      const updateData = {
        id: chartId as any as number,
        genChart: jsonCode,
      };

      const res = await updateChartUsingPost(updateData);

      if (res.code === 0) {
        message.success('图表配置更新成功');
      } else {
        message.error('更新失败: ' + res.message);
      }
    } catch (e: any) {
      message.error('更新失败: ' + e.message);
    } finally {
      setUpdating(false);
    }
  };

  /**
   * 轮询获取图表状态
   */
  const pollChartStatus = async () => {
    const maxAttempts = 30; // 最大尝试次数
    let attempts = 0;

    const poll = async () => {
      attempts++;
      try {
        const res = await getChartByIdUsingGet({ id: chartId });
        if (res.data) {
          setChart(res.data);
          // 更新JSON代码
          setJsonCode(res.data.genChart || '{}');

          // 如果图表还在生成中且未达到最大尝试次数，则继续轮询
          if (
            (res.data.status === 'wait' || res.data.status === 'running') &&
            attempts < maxAttempts
          ) {
            setTimeout(poll, 3000); // 每3秒查询一次
          } else if (attempts >= maxAttempts) {
            message.warning('图表生成时间过长，请稍后查看结果');
          }
        }
      } catch (e: any) {
        message.error('获取图表状态失败: ' + e.message);
      }
    };

    setTimeout(poll, 3000); // 3秒后开始第一次查询
  };

  /**
   * 下载图表图片
   */
  const handleDownloadChart = () => {
    if (!chartRef.current) {
      message.error('无法获取图表实例');
      return;
    }

    try {
      // 获取图表的 base64 图片数据
      const imgData = chartRef.current.getEchartsInstance().getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff',
      });

      // 创建下载链接
      const link = document.createElement('a');
      link.href = imgData;
      link.download = `${chart?.name || 'chart'}.png`;
      link.click();

      message.success('图表下载成功');
    } catch (e: any) {
      message.error('下载失败: ' + e.message);
    }
  };

  /**
   * 处理JSON代码变化
   */
  const handleJsonChange = (value: string | undefined) => {
    if (value !== undefined) {
      setJsonCode(value);
    }
  };

  /**
   * 重新渲染图表
   */
  const handleReRender = () => {
    try {
      // 验证JSON格式
      const parsedOption = JSON.parse(jsonCode);

      // 更新图表选项 - 使用正确的API
      if (chartRef.current) {
        const echartsInstance = chartRef.current.getEchartsInstance();
        echartsInstance.setOption(parsedOption, true); // 第二个参数为notMerge
      }

      message.success('图表重新渲染成功');
    } catch (e: any) {
      message.error('JSON格式错误: ' + e.message);
    }
  };

  // 处理图表高度变化
  const handleHeightChange = (value: number) => {
    setChartHeight(value);
  };

  // 处理图表宽度变化
  const handleWidthChange = (value: number) => {
    setChartWidth(value);
  };

  // 处理编辑器准备就绪
  const handleEditorDidMount = () => {
    setIsEditorReady(true);
  };

  useEffect(() => {
    fetchChartDetail();
  }, [chartId]);

  return (
    <PageContainer title="图表详情">
      <Card>
        <Spin spinning={loading}>
          {chart ? (
            <div>
              <Row gutter={[16, 16]}>
                <Col span={24}>
                  <Title level={4}>{chart.name}</Title>
                </Col>

                <Col span={12}>
                  <Text strong>分析目标：</Text>
                  <Text>{chart.goal}</Text>
                </Col>

                <Col span={12}>
                  <Text strong>图表类型：</Text>
                  <Text>{chart.chartType || '未指定'}</Text>
                </Col>

                <Col span={12}>
                  <Text strong>创建时间：</Text>
                  <Text>{chart.createTime}</Text>
                </Col>

                <Col span={12}>
                  <Text strong>更新时间：</Text>
                  <Text>{chart.updateTime}</Text>
                </Col>

                <Col span={12}>
                  <Text strong>状态：</Text>
                  <Text>
                    {chart.status === 'wait' && '等待生成'}
                    {chart.status === 'running' && '生成中'}
                    {chart.status === 'succeed' && '生成成功'}
                    {chart.status === 'failed' && '生成失败'}
                  </Text>
                </Col>

                {/* 修改：只有当状态不是生成成功时才显示执行信息 */}
                {chart.execMessage && chart.status !== 'succeed' && (
                  <Col span={24}>
                    <Text strong>执行信息：</Text>
                    <Text
                      type={chart.status === 'failed' ? 'danger' : 'secondary'}
                    >
                      {chart.execMessage}
                    </Text>
                  </Col>
                )}
              </Row>

              <Divider />

              <Row>
                <Col span={24}>
                  <Title level={5}>数据分析结果</Title>
                  <div>{chart.genResult}</div>
                </Col>
              </Row>

              <Divider />

              <Row>
                <Col span={24}>
                  <Title level={5}>图表展示与代码编辑</Title>
                  {chart.status === 'succeed' && chart.genChart ? (
                    <div
                      style={{
                        display: 'flex',
                        flexDirection: 'row',
                        height: '600px',
                      }}
                    >
                      {/* 左侧代码编辑区 */}
                      <div
                        style={{
                          flex: 1,
                          padding: 16,
                          borderRight: '1px solid #e8e8e8',
                          display: 'flex',
                          flexDirection: 'column',
                        }}
                      >
                        <div
                          style={{
                            marginBottom: 16,
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                          }}
                        >
                          <Text strong>JSON配置代码</Text>
                          <Button type="primary" onClick={handleReRender}>
                            重新渲染
                          </Button>
                        </div>
                        <div style={{ flex: 1, minHeight: 0 }}>
                          <Editor
                            height="100%"
                            defaultLanguage="json"
                            value={jsonCode}
                            onChange={handleJsonChange}
                            onMount={handleEditorDidMount}
                            options={{
                              minimap: { enabled: false },
                              wordWrap: 'on',
                              fontSize: 14,
                              theme: 'vs-dark',
                              automaticLayout: true,
                            }}
                          />
                        </div>
                      </div>

                      {/* 右侧图表展示区 */}
                      <div
                        style={{
                          flex: 1,
                          padding: 16,
                          display: 'flex',
                          flexDirection: 'column',
                        }}
                      >
                        <div
                          style={{
                            marginBottom: 16,
                            display: 'flex',
                            alignItems: 'center',
                          }}
                        >
                          <Text strong>调整图表高度：</Text>
                          <Slider
                            min={200}
                            max={800}
                            value={chartHeight}
                            step={50}
                            onChange={handleHeightChange}
                            style={{
                              marginLeft: 16,
                              width: 200,
                              display: 'inline-block',
                            }}
                          />
                          <Text style={{ marginLeft: 16 }}>
                            {chartHeight}px
                          </Text>
                        </div>
                        <div
                          style={{
                            marginBottom: 16,
                            display: 'flex',
                            alignItems: 'center',
                          }}
                        >
                          <Text strong>调整图表宽度：</Text>
                          <Slider
                            min={50}
                            max={100}
                            value={chartWidth}
                            step={5}
                            onChange={handleWidthChange}
                            style={{
                              marginLeft: 16,
                              width: 200,
                              display: 'inline-block',
                            }}
                          />
                          <Text style={{ marginLeft: 16 }}>{chartWidth}%</Text>
                        </div>
                        <div
                          style={{
                            width: `${chartWidth}%`,
                            flex: 1,
                            minHeight: 0,
                          }}
                        >
                          <ReactECharts
                            ref={chartRef}
                            option={JSON.parse(jsonCode)}
                            style={{ height: chartHeight, width: '100%' }}
                            notMerge={true}
                          />
                        </div>
                        <div style={{ textAlign: 'right', marginTop: 16 }}>
                          <Button onClick={handleDownloadChart}>
                            下载图表
                          </Button>
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div style={{ textAlign: 'center', padding: 40 }}>
                      {chart.status === 'wait' && '图表待生成'}
                      {chart.status === 'running' && '图表生成中...'}
                      {chart.status === 'failed' && '图表生成失败'}
                    </div>
                  )}
                </Col>
              </Row>

              {/* 对于未成功的图表，显示重新生成按钮 */}
              {chart.status !== 'succeed' && (
                <>
                  <Divider />
                  <Row>
                    <Col span={24} style={{ textAlign: 'center' }}>
                      <Button
                        type="primary"
                        loading={regenerating}
                        onClick={handleRegenerate}
                      >
                        重新生成图表
                      </Button>
                    </Col>
                  </Row>
                </>
              )}

              <Divider />

              <Row>
                <Col span={24} style={{ textAlign: 'right' }}>
                  <Button
                    onClick={handleUpdateChart}
                    loading={updating}
                    style={{ marginRight: 8 }}
                  >
                    更新图表
                  </Button>
                  <Button onClick={() => history.push('/my_chart')}>
                    返回我的图表
                  </Button>
                </Col>
              </Row>
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: 40 }}>
              无法加载图表详情
            </div>
          )}
        </Spin>
      </Card>
    </PageContainer>
  );
};

export default ChartDetailPage;
